package com.lianboke.link.ad.dbmanager;

import android.content.Context;
import android.text.TextUtils;

import com.lianboke.link.ad.app.MyApplication;
import com.lianboke.link.ad.entry.OrdetTypeTable;
import com.lianboke.link.ad.gen.OrdetTypeTableDao;
import com.lianboke.link.ad.utils.DateUtil;
import com.lianboke.link.ad.utils.KLog;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 订单详情数据库缓存
 * Created by admin on 2018/1/7.
 */

public class OrderDetailsCacheUtils {

    private static final String TAG = OrderDetailsCacheUtils.class.getSimpleName();
    private DaoManager mManager;

    public OrderDetailsCacheUtils(Context context) {
        mManager = DaoManager.getInstance();
        mManager.init(context);
    }

    /**
     * 添加订单详情记录
     * @param ordetType
     * @return
     */
    public long insertOrderTypeTable(OrdetTypeTable ordetType) {
        long insertId =  mManager.getDaoSession().getOrdetTypeTableDao().insertOrReplace(ordetType);
        return insertId;
    }

    /**
     * 插入多条数据，在子线程操作
     * @return
     */
    public boolean insertMultOrderTypes(final List<OrdetTypeTable> datasList) {
        boolean flag = false;
        try {
            mManager.getDaoSession().runInTx(new Runnable() {
                @Override
                public void run() {
                    for (OrdetTypeTable meizi : datasList) {
                        mManager.getDaoSession().insertOrReplace(meizi);
                    }
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 修改一条数据
     * @param ordetType
     * @return
     */
    public boolean updateOrderType(OrdetTypeTable ordetType){
        boolean flag = false;
        try {
            mManager.getDaoSession().update(ordetType);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 更新任务任务的认领和启动时间
     * @param orderId  ：
     * @param strTime  时间
     * @return
     */
    public boolean updateOrderTypeLaunchTimeByOrderId(long orderId,String strTime,OrdetTypeTable beanData){
        boolean flag = false;
        try {
            List<OrdetTypeTable> dbdatas = queryOrderTypeByOrderId(orderId);
            if(dbdatas!=null && !dbdatas.isEmpty()){
                OrdetTypeTable  dbdata = dbdatas.get(0);
                String strFirstTime = dbdata.getFirstLaunchTime();
                if(TextUtils.isEmpty(strFirstTime)){
                    dbdata.setFirstLaunchTime(strTime);
                }
                dbdata.setLastLaunchTime(strTime);
                mManager.getDaoSession().update(dbdata);
                flag = true;
            }else if(beanData!=null){
                if(TextUtils.isEmpty(beanData.getFirstLaunchTime())){
                    beanData.setLastLaunchTime(strTime);
                }
                beanData.setFirstLaunchTime(strTime);
                mManager.getDaoSession().insertOrReplace(beanData);
                flag = true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 更新任务的启动时间
     * @param appname
     * @param strTime
     * @return
     */
    public void updateOrderTypeLastTimeByAppName(String appname,String strTime){
        try {
            List<OrdetTypeTable> dbdatas = queryOrderTypeByAppName(appname);
            if(dbdatas!=null && !dbdatas.isEmpty()){
                for (OrdetTypeTable bean:dbdatas ) {
                    String strFirstTime = bean.getFirstLaunchTime();
                    if(TextUtils.isEmpty(strFirstTime)){
                        bean.setFirstLaunchTime(strTime);
                    }
                    bean.setLastLaunchTime(strTime);
                    mManager.getDaoSession().update(bean);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 删除单条记录
     * @param ordetType
     * @return
     */
    public boolean deleteOrdetType(OrdetTypeTable ordetType){
        boolean flag = false;
        try {
            //按照id删除
            mManager.getDaoSession().delete(ordetType);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 删除所有记录
     * @return
     */
    public boolean deleteAll(){
        boolean flag = false;
        try {
            //按照id删除
            mManager.getDaoSession().deleteAll(OrdetTypeTable.class);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }



    /**
     * 查询所有记录
     * @return
     */
    public List<OrdetTypeTable> queryAllOrderTypeCache(){
        return mManager.getDaoSession().loadAll(OrdetTypeTable.class);
    }
    /**
     * 根据主键id查询记录
     * @param key
     * @return
     */
    public OrdetTypeTable queryOrderTypeById(long key){
        return mManager.getDaoSession().load(OrdetTypeTable.class, key);
    }
    /**
     * 根据任务id 查询
     * @return
     */
    public List<OrdetTypeTable> queryOrderTypeByOrderId(long orderId){
        QueryBuilder<OrdetTypeTable> queryBuilder = mManager.getDaoSession().queryBuilder(OrdetTypeTable.class);
        queryBuilder.where(OrdetTypeTableDao.Properties.OrderId.eq(orderId));
        return queryBuilder.list();
    }
    /**
     * 根据任务appname 查询
     * @return
     */
    public List<OrdetTypeTable> queryOrderTypeByAppName(String appname){
        QueryBuilder<OrdetTypeTable> queryBuilder = mManager.getDaoSession().queryBuilder(OrdetTypeTable.class);
        queryBuilder.where(OrdetTypeTableDao.Properties.Appname.eq(appname));
        return queryBuilder.list();
    }
    /**
     * 根据任务appname 获取任务id
     * @return
     */
    public long queryOrderTypeIdByAppName(String appname){
        QueryBuilder<OrdetTypeTable> queryBuilder = mManager.getDaoSession().queryBuilder(OrdetTypeTable.class);
        queryBuilder.where(OrdetTypeTableDao.Properties.Appname.eq(appname));
        List<OrdetTypeTable> datasList = queryBuilder.list();
        if(datasList!=null && !datasList.isEmpty()){
            return datasList.get(0).getOrderId();
        }else{
            return -1;
        }
    }
    /**
     * 根据首次启动时间
     * @param firstTime
     * @return
     */
    public List<OrdetTypeTable> queryOrderTypeByOrderFirstTime(String firstTime){
        QueryBuilder<OrdetTypeTable> queryBuilder = mManager.getDaoSession().queryBuilder(OrdetTypeTable.class);
        queryBuilder.where(OrdetTypeTableDao.Properties.FirstLaunchTime.eq(firstTime));
        return queryBuilder.list();
    }

    /**
     * 根据最后启动时间查询
     * @param lastTime
     * @return
     */
    public List<OrdetTypeTable> queryOrderTypeByOrderLastTime(String lastTime){
        QueryBuilder<OrdetTypeTable> queryBuilder = mManager.getDaoSession().queryBuilder(OrdetTypeTable.class);
        queryBuilder.where(OrdetTypeTableDao.Properties.LastLaunchTime.eq(lastTime));
        return queryBuilder.list();
    }
    /**
     * 根据任务数据库 _id
     * @param _id
     * @return
     */
    public List<OrdetTypeTable> queryOrderTypeByOrderBy_Id(long _id){
        QueryBuilder<OrdetTypeTable> queryBuilder = mManager.getDaoSession().queryBuilder(OrdetTypeTable.class);
        queryBuilder.where(OrdetTypeTableDao.Properties._id.eq(_id));
        return queryBuilder.list();
    }
    /**
     * 根据需要启动时间查询
     * @param time
     * @return
     */
    public List<OrdetTypeTable> queryOrderTypeByOrderDurTime(String time){
        QueryBuilder<OrdetTypeTable> queryBuilder = mManager.getDaoSession().queryBuilder(OrdetTypeTable.class);
        queryBuilder.where(OrdetTypeTableDao.Properties.OrderId.isNotNull());
        List<OrdetTypeTable> dbData = queryBuilder.list();
        List<OrdetTypeTable> result = new ArrayList<OrdetTypeTable>();
        if(dbData!=null && !dbData.isEmpty()){
            for ( OrdetTypeTable bean : dbData ) {
                if(bean.getDurationLaunchTimes().contains(time) && (!bean.getLastLaunchTime().equals(time) || bean.getLastLaunchTime().isEmpty())){
                    result.add(bean);
                }
            }
        }
        return result;
    }

    /**
     * 获取未完成的任务列表
     * @return
     */
    public List<OrdetTypeTable> queryOrdersUnfinishDatas(){
        QueryBuilder<OrdetTypeTable> queryBuilder = mManager.getDaoSession().queryBuilder(OrdetTypeTable.class);
        queryBuilder.where(OrdetTypeTableDao.Properties.OrderId.isNotNull());
        List<OrdetTypeTable> orderDBDatas = queryBuilder.list();
        List<OrdetTypeTable> result = new ArrayList<OrdetTypeTable>();
        if(orderDBDatas!=null && !orderDBDatas.isEmpty()){
            for (OrdetTypeTable dbCacheBean:orderDBDatas) {
                StringBuffer sbNewDurationLaunchTime = new StringBuffer();
                String[] strTimesDatas = dbCacheBean.getDurationLaunchTimes().split("\\,");
                int iTimeDatasLength = strTimesDatas.length;
                long[] durationLaunchTimes = new long[iTimeDatasLength];
                for (int i=0;i<iTimeDatasLength;i++) {
                    //全部时间
                    long lTimeValue = DateUtil.getMillionSecondByDateFormat(strTimesDatas[i], "yyyy-MM-dd");
                    durationLaunchTimes[i] = lTimeValue;
                }
                int iTimeSize = 0;
                //排序操作
                if(durationLaunchTimes!=null && durationLaunchTimes.length>0){
                    iTimeSize = durationLaunchTimes.length;
                    Arrays.sort(durationLaunchTimes);
                }
                int pos = 0;
                for (int j=0;j<iTimeSize;j++) {
                   if(pos>0){
                       sbNewDurationLaunchTime.append(",");
                   }
                   String strTimeLog = DateUtil.longToString(durationLaunchTimes[j],"yyyy-MM-dd");
                    sbNewDurationLaunchTime.append(strTimeLog);
                   pos++;

                }
                dbCacheBean.setDurationLaunchTimes(sbNewDurationLaunchTime.toString());
                result.add(dbCacheBean);
            }
        }
        return result;
    }

    /**
     * 获取任务总数
     * @return
     */
    public int  queryOrderTypeAllCount(){
        try {
            QueryBuilder<OrdetTypeTable> queryBuilder = mManager.getDaoSession().queryBuilder(OrdetTypeTable.class);
            queryBuilder.where(OrdetTypeTableDao.Properties._id.isNotNull());
            return queryBuilder.list().size();
        }catch (Exception e){
            return 0;
        }
    }
    /**
     * 获取任务认领任务数量
     * @return
     */
    public int  queryOrderTypeStartCount(String time){
        try {
            QueryBuilder<OrdetTypeTable> queryBuilder = mManager.getDaoSession().queryBuilder(OrdetTypeTable.class);
            queryBuilder.where(OrdetTypeTableDao.Properties.FirstLaunchTime.eq(time));
            return queryBuilder.list().size();
        }catch (Exception e){
            return 0;
        }
    }
    /**
     * 获取任务总数
     * @return
     */
    public int  queryOrderTypeFinishCount(String time){
        try {
            QueryBuilder<OrdetTypeTable> queryBuilder = mManager.getDaoSession().queryBuilder(OrdetTypeTable.class);
            queryBuilder.where(OrdetTypeTableDao.Properties.LastLaunchTime.eq(time));
            return queryBuilder.list().size();
        }catch (Exception e){
            return 0;
        }
    }

    /**
     * 清楚过期任务
     * @param time
     * @return
     */
    public void clearPastDurOrder(String time){
        try {
            long currentTime = DateUtil.getMillionSecondByDateFormat(time, "yyyy-MM-dd");

            List<OrdetTypeTable> delOrderDBCacheDatas = new ArrayList<OrdetTypeTable>();//需要删除的缓存数据

            QueryBuilder<OrdetTypeTable> queryBuilder = mManager.getDaoSession().queryBuilder(OrdetTypeTable.class);
            queryBuilder.where(OrdetTypeTableDao.Properties.OrderId.isNotNull());
            List<OrdetTypeTable> dbCacheDatas = queryBuilder.list();
            if (dbCacheDatas != null && !dbCacheDatas.isEmpty()) {
                for (OrdetTypeTable dbCacheBean : dbCacheDatas) {
                    //全部数据
                    if (TextUtils.isEmpty(dbCacheBean.getDurationLaunchTimes())) {
                        //继续下次循环
                        delOrderDBCacheDatas.add(dbCacheBean);
                        MyApplication.appUnInstallPackNameDatas.add(dbCacheBean.getAppname());
                        continue;
                    }
                        String[] strTimesDatas = dbCacheBean.getDurationLaunchTimes().split("\\,");
                        int iTimeDatasLength = strTimesDatas.length;
                        long[] durationLaunchTimes = new long[iTimeDatasLength];
                        for (int i=0;i<iTimeDatasLength;i++) {
                            //全部时间
                            long lTimeValue = DateUtil.getMillionSecondByDateFormat(strTimesDatas[i], "yyyy-MM-dd");
                            durationLaunchTimes[i] = lTimeValue;
                        }
                        //排序操作
                        if(durationLaunchTimes!=null && durationLaunchTimes.length>0){
                            Arrays.sort(durationLaunchTimes);
                        }
                        //是否删除判断
                       // long lMixTime = durationLaunchTimes[0];
                        long lMaxTime = durationLaunchTimes[durationLaunchTimes.length-1];
                        if(lMaxTime<currentTime){
                            //最大时间，小于当前时间，认为任务过期
                            delOrderDBCacheDatas.add(dbCacheBean);
                            MyApplication.appUnInstallPackNameDatas.add(dbCacheBean.getAppname());
                        }
                }
                //删除过期任务
                for (OrdetTypeTable pastOrder: delOrderDBCacheDatas ) {
                    deleteOrdetType(pastOrder);
                }
            }
        }catch (Exception e){

        }
    }
}
